<!-- 商品发布 - 虚拟商品sku设置 -->
<template>
  <el-button v-if="!isDetail" @click="openForm(null)" type="primary">新增</el-button>
  <!--sku列表-->
  <el-table
    ref="activitySkuListRef"
    :data="formData!.skus!"
    border
    max-height="500"
    size="small"
    style="width: 99%;margin-top:16px;margin-bottom:24px;"
    @selection-change="handleSelectionChange"
  >
    <el-table-column align="center" label="SKU编号" min-width="80">
      <template #default="{ row }">
        {{row.id}}
      </template>
    </el-table-column>
    <el-table-column align="center" label="SKU名称" min-width="80">
    <template #default="{ row }">
      {{row.name}}
    </template>
    </el-table-column>
    <el-table-column align="center" label="SKU排序" min-width="80">
      <template #default="{ row }">
        {{row.sort}}
      </template>
    </el-table-column>
<!--    <el-table-column align="center" label="SKU信息" min-width="80">-->
<!--      <template #default="{ row }">-->
<!--        <el-image-->
<!--          v-if="row.picUrl"-->
<!--          :src="row.picUrl"-->
<!--          class="h-50px w-50px"-->
<!--          @click="imagePreview(row.picUrl)"-->
<!--        />-->
<!--      </template>-->
<!--    </el-table-column>-->
<!--    <el-table-column align="center" label="面值" min-width="80">-->
<!--      <template #default="{ row }">-->
<!--        {{row.denomination}}-->
<!--      </template>-->
<!--    </el-table-column>-->
    <el-table-column align="center" label="原价" min-width="80">
      <template #default="{ row }">
        {{row.marketPrice / 100 || 0}}
      </template>
    </el-table-column>
    <el-table-column align="center" label="售价" min-width="80">
      <template #default="{ row }">
        {{row.price / 100}}
      </template>
    </el-table-column>
    <el-table-column align="center" label="有效期（天）" min-width="80">
      <template #default="{ row }">
        {{row.esValidityPeriodDays}}
      </template>
    </el-table-column>
    <el-table-column align="center" label="流量大小（M）" min-width="80">
      <template #default="{ row }">
        {{row.esDataAllowanceMb}}
      </template>
    </el-table-column>
<!--    <el-table-column align="center" label="发货方式" min-width="80">-->
<!--      <template #default="{ row }">-->
<!--        {{ EnumDeliveryMethodTypeText[row.deliveryMethod] }}-->
<!--      </template>-->
<!--    </el-table-column>-->
    <el-table-column align="center" label="状态" min-width="80">
      <template #default="{ row }">
        <el-switch
          v-if="!isDetail"
          v-model="row.opeStatus"
          :loading="row.isLoading"
          @change="()=>{changeSkuStatusHandler(row)}"
          inline-prompt
          active-text="上架"
          inactive-text="下架"
        />
        <span v-else>
          {{EnumSkuStatusText[row.status]}}
        </span>
      </template>
    </el-table-column>
    <el-table-column align="center" label="创建时间" min-width="130">
      <template #default="{ row }">
        {{ row.createTimeText }}
      </template>
    </el-table-column>
    <el-table-column v-if="!isDetail" align="center" fixed="right" label="操作" width="150">
      <template #default="{ row }">
        <el-button @click="copyToCreate(row)" link size="small" type="primary" :data-id="row.id">
          复制
        </el-button>
        <el-button @click="openForm(row)" link size="small" type="primary" >
          修改
        </el-button>
<!--        <el-button link size="small" type="primary" >删除</el-button>-->
      </template>
    </el-table-column>
  </el-table>

  <VirtualProductSkuUpdateForm @create-success="closeAndRefresh" @update-success="closeAndRefresh" :is-detail="isDetail" :spu-id="props.id" ref="formRef" />
</template>
<script lang="ts" setup>
import type { Spu } from '@/api/mall/product/spu'
import {getSkuList, updateSkuStatus} from '@/api/mall/product/spu'
import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import {ElTable} from "element-plus";
import {createImageViewer} from "@/components/ImageViewer";
import VirtualProductSkuUpdateForm from './../components/VirtualProductSkuUpdateForm.vue';
import {EnumDeliveryMethodTypeText, EnumSkuStatusText} from "@/config/spu";
import dayjs from 'dayjs';

defineOptions({ name: 'ProductVirtualProductSkuForm' })

const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  id: propTypes.number.def(undefined),
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
})

const formRef = ref() // 表单Ref
// 表单数据
const formData = ref({
  skus: [],
})

const validate = async () => {
  if (!formRef) return

  if(!props.propFormData?.virtualProduct) {
    return;
  }

  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData.value)
  } catch (e) {
    message.error('【虚拟商品SKU】不完善，请填写相关信息')
    throw e // 目的截断之后的校验
  }
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    zIndex: 9999999,
    urlList: [imgUrl]
  })
}

const openForm = (obj?: any)=> {
  formRef.value.open(obj);
}

const copyToCreate = (obj: any)=> {
  let newObj: any = {
    ...obj
  };

  delete newObj.id;
  delete newObj.cardKeyProductNo;
  delete newObj.picUrl;
  delete newObj.createTime;

  formRef.value.open(newObj);
}

const changeSkuStatusHandler = (sku)=> {
  sku.isLoading = true;
  updateSkuStatus({
    id: sku.id,
    status: +sku.opeStatus
  }).then(()=> {
    message.success("更新成功");
  }).catch(()=> {
    sku.opeStatus = !sku.opeStatus;
  }).finally(()=> {
    sku.isLoading = false;
  })
}

const getList = async ()=> {
  let res = await getSkuList({spuId: props.id});

  if(!res) {
    return;
  }

  formData.value.skus = res.map(e=> {
    e.opeStatus = !!e.status;
    e.createTimeText = dayjs(e.createTime).format("YYYY-MM-DD hh:mm:ss");

    return e;
  });
}

const closeAndRefresh = ()=> {
  unref(formRef).close();
  getList();
}

defineExpose({ validate, formData })

onMounted(async ()=> {
  await getList();
})
</script>
